# -*- coding: utf-8 -*-
import os
import shutil
import subprocess


class Utils:

	@staticmethod
	def check_and_mkdir(path):
		if not os.path.exists(path):
			os.mkdir(path)

	@staticmethod
	def err_print(msg): # red
		print('\033[91m' + msg + '\033[0m')

	@staticmethod
	def notice_print(msg): # blue
		print('\033[94m' + msg + '\033[0m')

	@staticmethod
	def exec_command(cmd, cwd):
		print(f"Run cmd '{cmd}' in '{cwd}'")
		try:
			result = subprocess.run(cmd, cwd=cwd, shell=True) # capture_output=True
			if result.returncode != 0:
				msg = f"returncode: {result.returncode} cmd: '{result.args}' err:{result.stderr}"
				Utils.err_print(msg)
				return False
		except Exception as ex:
			import traceback
			traceback.print_exc()
			Utils.err_print(f"Failed to execute cmd '{cmd}' in dir '{cwd}'")
			return False
		return True

	@staticmethod
	def print_trace():
		import traceback
		traceback.print_exc()

	@staticmethod
	def remove_dir(path):
		if not os.path.exists(path):
			return
		for root, dirs, files in os.walk(path, topdown=False):
			for name in files:
				os.remove(os.path.join(root, name))
			for name in dirs:
				os.rmdir(os.path.join(root, name))
		os.rmdir(path)
		Utils.notice_print(f"Remove dir: {path}")

	@staticmethod
	def remove_path(path):
		if os.path.isdir(path):
			Utils.remove_dir(path)
		else:
			if os.path.exists(path):
				os.remove(path)

	@staticmethod
	def copy_dir(src, dst):
		try:
			shutil.copytree(src, dst)
		except IOError as io_err:
			os.makedirs(dst)
			shutil.copytree(src, dst)
		Utils.notice_print(f"Copy dir {src} to {dst}")

	@staticmethod
	def log_to_file(fi, msg):
		with open(fi, "a+") as fp:
			fp.write(msg)
